from person import app, db
from person.models import *
from flask import request, url_for, redirect, flash, render_template
from flask_security import SQLAlchemyUserDatastore, Security, current_user, login_required
from flask_security.utils import login_user, logout_user
from person import forms
import datetime, time

# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)

security = Security(app, user_datastore)
db.create_all()


@app.route('/', methods=['GET', 'POST'])
def index():
    nowtrue = Staff.query.filter_by(now=True).all()
    nowfalse = Staff.query.filter_by(now = False).all()

    men = Staff.query.filter_by(sex='男').all()
    women = Staff.query.filter_by(sex='女').all()
    return render_template('index.html',nowtrue=nowtrue,nowfalse=nowfalse,men=men,women=women)


"""
 负责的功能
 注册--logging
 登录--login
 登出--logout
 权限管理--'User','Admin','Root'
 员工入职管理 -- staff --填写/write_staff(user/admin) -- 修改/change_staff(user/Admin) -- 离职处理/dimission(User)(修改now属性为0)
                        --查找/select_staff(userID,username,IDnumber,departmentID,departmentname,)
            -- staff_probation --填写/write_staff_probation(Admin) -- 修改/change_staff_probation(Admin)
 员工离职管理 -- staff_dimission --填写/write_staff_dimission(Admin) -- 修改/change_staff_dimission(Admin)
                            -- 查找/select_staff_dimission(userID,name,departmentname,postname,dimission_type,date)
 员工信息中心 
        -- staff_information
              -- staff_career -- 填写/write_staff_career(user/Admin)  --修改/change_staff_career(user/Admin)
              -- staff_languages -- 填写/write_staff_languages(user/Admin) -- 修改/change_Staff_languages(user/Admin)
        -- staff_relation  -- 填写/write_staff_relation(user/Admin)  -- 修改/change_Staff_relation(user/Admin)
                           -- 删除/del_staff_relation(user/Admin)
        -- 查找/select_staff_information (Admin)(userID,username)    
 用户权限管理 -- user_role (Admin/Root)    -- 修改/change_role (提升为管理员，降为普通用户)（Root）
"""


@app.route('/user/login', methods=['GET', 'POST'])
def login():  # 登录
    if not current_user.is_anonymous:
        return redirect(url_for('index'))
    form = forms.LoginForm()
    if request.method == 'POST':
        userID = request.form.get('userID')
        password = request.form.get('password')

        if not userID or not password:
            flash('请输入')
            return redirect(url_for('login'))

        user = User.query.filter_by(userID=userID).first()
        if user is None:
            flash('员工号错误')
            return redirect(url_for('login'))
        now = Staff.query.filter_by(now=True,userID=user.userID).first()
        if now is None:
            flash('员工已离职')
            return redirect(url_for('login'))
        if not user.validate_password(password):
            flash('密码错误')
            return redirect(url_for('login'))
        flash('登录成功')
        login_user(user, remember=True)
        return redirect(url_for('index'))
    return render_template('login.html', form=form)


@app.route('/logging', methods=['GET', 'POST'])
def logging():  # 注册
    if not current_user.is_anonymous:
        return redirect(url_for('index'))
    if request.method == 'POST':
        userID = request.form.get('userID')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')
        phone = request.form.get('phone')
        email = request.form.get('email')
        if password1 != password2:
            flash('两次输入的密码不同')
            return redirect(url_for('logging'))
        staff = Staff.query.filter_by(userID=userID).first()
        if staff is None:
            flash('员工号错误')
            return redirect(url_for('logging'))
        now = Staff.query.filter_by(now=True, userID=userID).first()
        if now is None:
            flash('员工已离职')
            return redirect(url_for('logging'))
        user = User.query.filter_by(userID=userID).first()
        if user is not None:
            flash('用户已注册')
            return redirect(url_for('login'))
        user = Staff.query.filter_by(userID=userID).first()
        if user is None:
            flash('用户不存在，请检查员工号')
            return redirect(url_for('logging'))
        new_user = user_datastore.create_user(userID=userID, password=User.set_password(password1), phone=phone,
                                              email=email)
        normal_role = user_datastore.find_role('User')
        db.session.add(new_user)
        user_datastore.add_role_to_user(new_user, normal_role)
        db.session.commit()
        login_user(new_user)
        return redirect(url_for('index'))
    return render_template('logging.html')


@app.route('/logout')
def logout():  # 登出
    logout_user()
    flash('登出')
    return redirect(url_for('index'))


@app.route('/staff',methods=['GET','POST'])
@login_required  # 用于视图保护
def staff():  # 员工基本信息
    if current_user.has_role('Admin')  or current_user.has_role('Root'):
        if request.method == 'POST':
            info = request.form.get('info')
            date = request.form.get('date')
            if info == 'userID':
                staffs = Staff.query.filter_by(userID=date,now=True).first()
                if staffs is None:
                    flash('员工号不存在')
                    return redirect(url_for('staff'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()

                return render_template('staff.html',staffs=staffs, departments=departments, posts=posts,info=info)
            if info == 'username':
                staffs = Staff.query.filter_by(username=date,now=True).first()
                if staffs is None:
                    flash('员工不存在')
                    return redirect(url_for('staff'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()

                return render_template('staff.html',staffs=staffs, departments=departments, posts=posts,info=info)
            if info == 'IDnumber':
                staffs = Staff.query.filter_by(IDnumber=date,now=True).first()
                if staffs is None:
                    flash('员工不存在')
                    return redirect(url_for('staff'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()

                return render_template('staff.html',staffs=staffs, departments=departments, posts=posts,info=info)
            if info == 'departmentID':
                staffs = Staff.query.filter_by(departmentID=date,now=True).all()
                if staffs is None:
                    flash('部门号不存在')
                    return redirect(url_for('staff'))
                departments = Department.query.filter_by(departmentID=date).first()
                if departments is None:
                    flash('部门号不存在')
                    return redirect(url_for('staff'))
                posts = Post.query.all()

                return render_template('staff.html',staffs=staffs, departments=departments, posts=posts,info=info)
            if info == 'departmentname':
                departments = Department.query.filter_by(departmentname=date).first()
                if departments is None:
                    flash('部门不存在')
                    return redirect(url_for('staff'))
                staffs = Staff.query.filter_by(departmentID=departments.departmentID,now=True).all()
                posts = Post.query.all()

                return render_template('staff.html',staffs=staffs, departments=departments, posts=posts,info=info)
        staffs = Staff.query.filter_by(now=True).all()
        departments = Department.query.all()
        posts = Post.query.all()
        info = 1
        return render_template('staff.html', staffs=staffs, departments=departments, posts=posts,info=info)
    elif current_user.has_role('User'):
        staffs = Staff.query.filter_by(userID=current_user.userID).first()
        departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
        posts = Post.query.filter_by(postID=staffs.postID).first()
        return render_template('staff.html', staffs=staffs, departments=departments, posts=posts)

@app.route('/detailed_staff/<int:userID>')
@login_required  # 用于视图保护
def detailed_staff(userID):  # 详细信息
    staff = Staff.query.get_or_404(userID)
    department = Department.query.filter_by(departmentID=staff.departmentID).first()
    post = Post.query.filter_by(postID=staff.postID).first()
    return render_template('detailed_staff.html',staff=staff,department=department,post=post)

@app.route('/write_staff', methods=['GET', 'POST'])
def write_staff():  # 填写员工基本信息
    departments = Department.query.all()
    posts = Post.query.all()
    nations = Nation.query.all()
    if request.method == 'POST':
        if not current_user.is_authenticated:
            return redirect(url_for('index'))
        else:
            username = request.form.get('username')
            sex = request.form.get('sex')
            birthday = request.form.get('birthday')
            IDnumber = request.form.get('IDnumber')
            departmentID = request.form.get('departmentID')
            postID = request.form.get('postID')
            hiredate = request.form.get('hiredate')
            takejobdate = request.form.get('takejobdate')
            employment_form = request.form.get('employment_form')
            personnel_source = request.form.get('personnel_source')
            phone = request.form.get('phone')
            email = request.form.get('email')
            politics_status = request.form.get('politics_status')
            nation = request.form.get('nation')
            native_place = request.form.get('native_place')
            height = request.form.get('height')
            if height == '':
                height = None
            bloodtype = request.form.get('bloodtype')
            marriage = request.form.get('marriage')
            birthplace = request.form.get('birthplace')
            domicileplace = request.form.get('domicileplace')
            highest_degree = request.form.get('highest_degree')
            highest_offering = request.form.get('highest_offering')
            graduate_school = request.form.get('graduate_school')
            major = request.form.get('major')
            graduation_date = request.form.get('graduation_date')
            if graduation_date == '':
                graduation_date = None
            startdate = request.form.get('startdate')
            enddate = request.form.get('enddate')
            staff_phone = Staff.query.filter_by(phone=phone).first()
            if staff_phone is not None:
                flash('电话号码已存在')
                return redirect(url_for('write_staff'))
            staff_email = Staff.query.filter_by(email=email).first()
            if staff_email is not None:
                flash('邮箱已存在')
                return redirect(url_for('write_staff'))
            print("输入")
            staff = Staff(username=username, sex=sex, birthday=birthday, IDnumber=IDnumber,
                          departmentID=departmentID, postID=postID, hiredate=hiredate,
                          takejobdate=takejobdate, employment_form=employment_form,
                          personnel_source=personnel_source, phone=phone, email=email, now=True,
                          politics_status=politics_status,nation=nation,native_place=native_place,
                          height=height,bloodtype=bloodtype,marriage=marriage,birthplace=birthplace,
                          domicileplace=domicileplace,highest_degree=highest_degree,
                          highest_offering=highest_offering,graduate_school=graduate_school,
                          major=major,graduation_date=graduation_date)
            db.session.add(staff)
            db.session.commit()
            user = Staff.query.filter_by(IDnumber = IDnumber).first()
            staff_probation = Staff_probation(userID = user.userID,startdate=startdate,enddate=enddate)
            db.session.add(staff_probation)
            db.session.commit()
            flash('添加成功')
            return redirect(url_for('staff'))

    return render_template('write_staff.html', departments=departments, posts=posts,nations=nations)

@app.route('/change_staff/<int:userID>',methods=['GET','POST'])
@login_required
def change_staff(userID):  # 修改员工基本信息
    staff = Staff.query.get_or_404(userID)
    departments = Department.query.all()
    posts = Post.query.all()
    nations = Nation.query.all()
    if request.method == 'POST':
        username = request.form.get('username')
        departmentID = request.form.get('departmentID')
        postID = request.form.get('postID')
        employment_form = request.form.get('employment_form')
        phone = request.form.get('phone')
        email = request.form.get('email')
        politics_status = request.form.get('politics_status')
        nation = request.form.get('nation')
        native_place = request.form.get('native_place')
        height = request.form.get('height')
        if height == '':
            height = None
        bloodtype = request.form.get('bloodtype')
        marriage = request.form.get('marriage')
        birthplace = request.form.get('birthplace')
        domicileplace = request.form.get('domicileplace')
        highest_degree = request.form.get('highest_degree')
        highest_offering = request.form.get('highest_offering')
        graduate_school = request.form.get('graduate_school')
        major = request.form.get('major')
        graduation_date = request.form.get('graduation_date')
        if graduation_date == '':
            graduation_date = None
        staff_phone = Staff.query.filter_by(phone=phone).first()
        if staff_phone is not None:
            if staff_phone.userID != userID:
                flash('电话号码已存在')
                return redirect(url_for('change_staff',userID=userID))
        staff_email = Staff.query.filter_by(email=email).first()
        if staff_email is not None:
            if staff_email.userID != userID:
                flash('邮箱已存在')
                return redirect(url_for('change_staff',userID=userID))
        staff.username=username
        staff.departmentID = departmentID
        staff.postID = postID
        staff.employment_form=employment_form
        staff.politics_status=politics_status
        staff.nation=nation
        staff.native_place=native_place
        staff.phone=phone
        staff.email=email
        staff.height=height
        staff.bloodtype=bloodtype
        staff.marriage=marriage
        staff.birthplace=birthplace
        staff.domicileplae=domicileplace
        staff.highest_degree =highest_degree
        staff.highest_offering=highest_offering
        staff.graduate_school=graduate_school
        staff.major=major
        staff.graduation_date=graduation_date
        db.session.commit()
        flash('更新成功')
        return redirect(url_for('staff'))
    return render_template('change_staff.html',staff=staff,departments=departments,posts=posts,nations=nations)



@app.route('/write_staff_dimission/<int:userID>',methods=['GET','POST'])
@login_required
def write_staff_dimission(userID):  # 填写员工离职信息
    staff = Staff.query.get_or_404(userID)
    if request.method == 'POST':
        userID=userID
        termdate = request.form.get('termdate')
        dimission_type = request.form.get('dimission_type')
        leave_to = request.form.get('leave_to')
        talent_pool = request.form.get('talent_pool')
        remark = request.form.get('remark')
        staff_dimission = Staff_dimission(userID=userID,termdate=termdate,dimission_type=dimission_type,
                                          leave_to=leave_to,talent_pool=talent_pool,remark=remark)
        db.session.add(staff_dimission)
        staff.now = False
        db.session.commit()
        flash('修改成功')
        return redirect(url_for('staff'))
    return render_template('/write_staff_dimission.html',staff=staff)


@app.route('/staff_dimission',methods=['GET','POST'])
@login_required
def staff_dimission():  # 查看员工离职信息
    if current_user.has_role('Admin') or current_user.has_role('Root'):
        if request.method == 'POST':
            info = request.form.get('info')
            date = request.form.get('date')
            if info == 'userID':
                staffs = Staff.query.filter_by(userID=date,now = False).first()
                if staffs is None:
                    flash('员工号不存在或员工未离职')
                    return redirect(url_for('staff_dimission'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()
                staff_dimissions = Staff_dimission.query.filter_by(userID=date).first()
                return render_template('staff_dimission.html',staff_dimissions=staff_dimissions,staffs=staffs, departments=departments, posts=posts,info=info)
            if info == 'username':
                staffs = Staff.query.filter_by(username=date,now =False).first()
                if staffs is None:
                    flash('员工不存在或员工未离职')
                    return redirect(url_for('staff_dimission'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()
                staff_dimissions = Staff_dimission.query.filter_by(userID=staffs.userID).first()
                return render_template('staff_dimission.html',staff_dimissions=staff_dimissions,staffs=staffs, departments=departments, posts=posts,info=info)
            if info == 'departmentname':
                departments = Department.query.filter_by(departmentname=date).first()
                if departments is None:
                    flash('部门不存在')
                    return redirect(url_for('staff_dimission'))
                staffs = Staff.query.filter_by(departmentID=departments.departmentID,now=False).all()
                if staffs is None:
                    flash('该部门不存在离职员工')
                    return redirect(url_for('staff_dimission'))
                posts = Post.query.all()
                staff_dimissions=Staff_dimission.query.all()
                return render_template('staff_dimission.html',staff_dimissions=staff_dimissions,staffs=staffs, departments=departments, posts=posts,info=info)
            if info == 'postname':
                posts = Post.query.filter_by(postname=date).first()
                if posts is None:
                    flash('岗位不存在')
                    return  redirect(url_for('staff_dimission'))
                staffs = Staff.query.filter_by(postID = posts.postID,now = False).all()
                if staffs is None:
                    flash('该岗位不存在离职员工')
                    return redirect(url_for('staff_dimission'))
                departments = Department.query.all()
                staff_dimissions = Staff_dimission.query.all()
                return render_template('staff_dimission.html', staff_dimissions=staff_dimissions, staffs=staffs,
                                       departments=departments, posts=posts, info=info)
            if info == 'dimission_type':
                staff_dimissions = Staff_dimission.query.filter(Staff_dimission.dimission_type.like('%{date}%'.format(date=date))).all()
                if staff_dimissions is None:
                    flash('该类型没有离职员工')
                    return  redirect(url_for('staff_dimission'))
                staffs = Staff.query.filter_by(now=False).all()
                departments = Department.query.all()
                posts = Post.query.all()
                return render_template('staff_dimission.html', staff_dimissions=staff_dimissions, staffs=staffs,
                                       departments=departments, posts=posts, info=info)
            if info == 'termdate':
                staff_dimissions = Staff_dimission.query.filter(Staff_dimission.termdate <= date).all()
                if staff_dimissions is None:
                    flash('该时间之前没有离职员工')
                    return redirect(url_for('staff_dimission'))
                staffs = Staff.query.filter_by(now=False).all()
                departments = Department.query.all()
                posts = Post.query.all()
                return render_template('staff_dimission.html', staff_dimissions=staff_dimissions, staffs=staffs,
                                       departments=departments, posts=posts, info=info)
        staff_dimissions =Staff_dimission.query.all()
        staffs = Staff.query.filter_by(now = False).all()
        departments = Department.query.all()
        posts = Post.query.all()
        info = 1
        return render_template('/staff_dimission.html',staff_dimissions=staff_dimissions,staffs=staffs,departments=departments,posts=posts,info=info)

@app.route('/change_staff_dimission/<int:userID>',methods=['GET','POST'])
@login_required
def change_staff_dimission(userID):  # 修改员工离职信息
    staff = Staff.query.get_or_404(userID)
    staff_dimission = Staff_dimission.query.filter_by(userID=userID).first()
    if staff_dimission is None:
        flash('员工未离职')
        return redirect(url_for('staff_dimission'))

    if request.method == 'POST':
        dimission_type = request.form.get('dimission_type')
        leave_to = request.form.get('leave_to')
        remark = request.form.get('remark')
        staff_dimission.dimission_type = dimission_type
        staff_dimission.leave_to=leave_to
        staff_dimission.remark = remark
        db.session.commit()
        flash('更新成功')
        return redirect(url_for('staff_dimission'))
    return render_template('change_staff_dimission.html',staff=staff,staff_dimission=staff_dimission)


@app.route('/user_role',methods=['GET','POST'])
@login_required
def user_role():
    if current_user.has_role('Root'):
        if request.method == 'POST':
            info = request.form.get('info')
            date = request.form.get('date')
            if info == 'userID':
                staffs = Staff.query.filter_by(userID=date,now=True).first()
                if staffs is None:
                    flash('员工号不存在或已离职')
                    return redirect(url_for('user_role'))
                users = User.query.filter_by(userID=date).first()

                return render_template('user_role.html',users=users,staffs=staffs,info=info)
            if info == 'username':
                staffs = Staff.query.filter_by(username=date,now=True).first()
                if staffs is None:
                    flash('员工号不存在或已离职')
                    return redirect(url_for('user_role'))
                users = User.query.filter_by(userID=staffs.userID).first()

                return render_template('user_role.html',users=users,staffs=staffs,info=info)
        users = User.query.all()
        staffs = Staff.query.filter_by(now=True).all()

        info = 1
        return render_template('user_role.html',users=users,staffs=staffs,info=info)
    else:
        flash('请以超级管理员账户登录')
        return redirect(url_for('index'))


@app.route('/promote_role/<int:userID>')
@login_required
def promote_role(userID):  # 升为管理员
    user = User.query.filter_by(userID=userID).first()
    adminrole = user_datastore.find_role('Admin')
    userrole = user_datastore.find_role('User')
    user_datastore.remove_role_from_user(user,userrole)
    user_datastore.add_role_to_user(user, adminrole)
    db.session.commit()
    return redirect(url_for('user_role'))

@app.route('/reduce_role/<int:userID>')
@login_required
def reduce_role(userID):  # 降为普通用户
    user = User.query.filter_by(userID=userID).first()
    adminrole = user_datastore.find_role('Admin')
    userrole = user_datastore.find_role('User')
    user_datastore.remove_role_from_user(user,adminrole)
    user_datastore.add_role_to_user(user, userrole)
    db.session.commit()
    return redirect(url_for('user_role'))

@app.route('/staff_information',methods=['GET','POST'])
@login_required
def staff_information():  # 员工信息中心主界面
    if current_user.has_role('Admin')  or current_user.has_role('Root'):
        if request.method == 'POST':
            info = request.form.get('info')
            date = request.form.get('date')
            if info == 'userID':
                staffs = Staff.query.filter_by(userID=date).first()
                if staffs is None:
                    flash('员工号不存在')
                    return redirect(url_for('staff_information'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()

                return render_template('staff_information.html',staffs=staffs, departments=departments, posts=posts,info=info)
            if info == 'username':
                staffs = Staff.query.filter_by(username=date).first()
                if staffs is None:
                    flash('员工不存在')
                    return redirect(url_for('staff_information'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()

                return render_template('staff_information.html',staffs=staffs, departments=departments, posts=posts,info=info)
            if info == 'IDnumber':
                staffs = Staff.query.filter_by(IDnumber=date).first()
                if staffs is None:
                    flash('员工不存在')
                    return redirect(url_for('staff_information'))
                departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
                posts = Post.query.filter_by(postID=staffs.postID).first()

                return render_template('staff_information.html',staffs=staffs, departments=departments, posts=posts,info=info)
            if info == 'departmentID':
                staffs = Staff.query.filter_by(departmentID=date).all()
                if staffs is None:
                    flash('部门号不存在')
                    return redirect(url_for('staff_information'))
                departments = Department.query.filter_by(departmentID=date).first()
                if departments is None:
                    flash('部门号不存在')
                    return redirect(url_for('staff_information'))
                posts = Post.query.all()

                return render_template('staff_information.html',staffs=staffs, departments=departments, posts=posts,info=info)
            if info == 'departmentname':
                departments = Department.query.filter_by(departmentname=date).first()
                if departments is None:
                    flash('部门不存在')
                    return redirect(url_for('staff_information'))
                staffs = Staff.query.filter_by(departmentID=departments.departmentID).all()
                posts = Post.query.all()

                return render_template('staff_information.html',staffs=staffs, departments=departments, posts=posts,info=info)
        staffs=Staff.query.filter_by(now = True).all()
        departments = Department.query.all()
        posts = Post.query.all()
        info = 1
        return render_template('staff_information.html',staffs=staffs,departments=departments,posts=posts,info=info)
    elif current_user.has_role('User'):
        staffs = Staff.query.filter_by(userID=current_user.userID).first()
        departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
        posts = Post.query.filter_by(postID=staffs.postID).first()
        return render_template('staff_information.html', staffs=staffs, departments=departments, posts=posts)


@app.route('/staff_career/<int:userID>')
@login_required
def staff_career(userID):
    staff_careers = Staff_career.query.filter_by(userID=userID).all()
    staff = Staff.query.filter_by(userID=userID).first()
    return render_template('staff_career.html',staff_careers=staff_careers,staff=staff,userID=userID)

@app.route('/detailed_staff_career/<int:userID>/<int:id>')
@login_required
def detailed_staff_career(userID,id):
    staff_career = Staff_career.query.get_or_404(id)
    staff = Staff.query.filter_by(userID=userID).first()
    return render_template('detailed_staff_career.html',staff_career=staff_career,staff=staff)

@app.route('/staff_career_delete/<int:userID>/<int:id>',methods=['POST'])
@login_required  # 登录保护
def staff_career_delete(id,userID):
    staff_career = Staff_career.query.get_or_404(id)

    db.session.delete(staff_career)
    db.session.commit()
    flash('删除成功')
    return redirect(url_for('staff_career',userID=userID))

@app.route('/write_staff_career/<int:userID>',methods=['GET','POST'])
@login_required
def write_staff_career(userID):
    staff = Staff.query.filter_by(userID=userID).first()
    if request.method == 'POST':
        userID = userID
        starttime = request.form.get('starttime')
        endtime = request.form.get('endtime')
        company_name = request.form.get('company_name')
        job_content = request.form.get('job_content')
        duty = request.form.get('duty')
        pay = request.form.get('pay')
        certifier = request.form.get('certifier')
        certifier_duty = request.form.get('certifier_duty')
        certifier_phone = request.form.get('certifier_phone')
        if certifier_phone == '':
            certifier_phone = None
        remark = request.form.get('remark')
        staff_career = Staff_career(userID=userID,starttime=starttime,endtime=endtime,
                                    company_name=company_name,job_content=job_content,
                                    duty=duty,pay=pay,certifier=certifier,certifier_duty=certifier_duty,
                                    certifier_phone=certifier_phone,remark=remark)
        db.session.add(staff_career)
        db.session.commit()
        flash('添加成功')
        return redirect(url_for('staff_career',userID=userID))
    return render_template('write_staff_career.html',staff=staff)

@app.route('/change_staff_career/<int:userID>/<int:id>',methods=['GET','POST'])
@login_required
def change_staff_career(userID,id):
    staff_career = Staff_career.query.filter_by(userID=userID,id=id).first()
    staff = Staff.query.filter_by(userID=userID).first()
    if request.method == 'POST':
        starttime = request.form.get('starttime')
        endtime = request.form.get('endtime')
        company_name = request.form.get('company_name')
        job_content = request.form.get('job_content')
        duty = request.form.get('duty')
        pay = request.form.get('pay')
        certifier = request.form.get('certifier')
        certifier_duty = request.form.get('certifier_duty')
        certifier_phone = request.form.get('certifier_phone')
        if certifier_phone == '':
            certifier_phone = None
        remark = request.form.get('remark')

        staff_career.starttime=starttime
        staff_career.endtime=endtime
        staff_career.company_name=company_name
        staff_career.job_content=job_content
        staff_career.duty=duty
        staff_career.pay=pay
        staff_career.certifier=certifier
        staff_career.certifier_duty=certifier_duty
        staff_career.certifier_phone=certifier_phone
        staff_career.remark=remark

        db.session.commit()
        flash('更新成功')
        return redirect(url_for('staff_career',userID=userID))
    return render_template('change_staff_career.html', staff_career=staff_career,staff=staff)

@app.route('/staff_languages/<int:userID>')
@login_required
def staff_languages(userID):
    staff_languages = Staff_languages.query.filter_by(userID=userID).all()
    staff = Staff.query.filter_by(userID=userID).first()
    return render_template('staff_languages.html',staff_languages=staff_languages,staff=staff,userID=userID)

@app.route('/staff_languages_delete/<int:userID>/<int:id>',methods=['POST'])
@login_required  # 登录保护
def staff_languages_delete(id,userID):
    staff_languages = Staff_languages.query.get_or_404(id)

    db.session.delete(staff_languages)
    db.session.commit()
    flash('删除成功')
    return redirect(url_for('staff_languages',userID=userID))

@app.route('/write_staff_languages/<int:userID>',methods=['GET','POST'])
@login_required
def write_staff_languages(userID):
    staff = Staff.query.filter_by(userID=userID).first()
    if request.method == 'POST':
        userID = userID
        language = request.form.get('language')
        prificiency = request.form.get('prificiency')
        staff_languages = Staff_languages(userID=userID,language=language,prificiency=prificiency)
        db.session.add(staff_languages)
        db.session.commit()
        flash('添加成功')
        return redirect(url_for('staff_languages',userID=userID))
    return render_template('write_staff_languages.html',staff=staff)


@app.route('/change_staff_languages/<int:userID>/<int:id>',methods=['GET','POST'])
@login_required
def change_staff_languages(userID,id):
    staff_language = Staff_languages.query.filter_by(userID=userID,id=id).first()
    staff = Staff.query.filter_by(userID=userID).first()
    if request.method == 'POST':
        language = request.form.get('language')
        prificiency = request.form.get('prificiency')

        staff_language.language=language
        staff_language.prificiency=prificiency

        db.session.commit()
        flash('更新成功')
        return redirect(url_for('staff_languages',userID=userID))
    return render_template('change_staff_languages.html', staff_language=staff_language,staff=staff)


@app.route('/staff_relation/<int:userID>')
@login_required
def staff_relation(userID):
    staff_relations = Staff_relation.query.filter_by(userID=userID).all()
    staff = Staff.query.filter_by(userID=userID).first()
    return render_template('staff_relation.html',staff_relations=staff_relations,staff=staff,userID=userID)


@app.route('/write_staff_relation/<int:userID>',methods=['GET','POST'])
@login_required
def write_staff_relation(userID):
    staff = Staff.query.filter_by(userID=userID).first()

    if request.method == 'POST':
        userID = userID
        relation = request.form.get('relation')
        staff_relation = Staff_relation.query.filter_by(userID=userID,relation=relation).first()
        if staff_relation is not None:
            flash('已存在此关系，请删除后重新添加')
            return redirect(url_for('staff_relation', userID=userID))
        name = request.form.get('name')
        company = request.form.get('company')
        position = request.form.get('position')
        phone = request.form.get('phone')
        if phone == '':
            phone = None
        staff_relation = Staff_relation(userID=userID,relation=relation,name=name,
                                        company=company,position=position,phone=phone)
        db.session.add(staff_relation)
        db.session.commit()
        flash('添加成功')
        return redirect(url_for('staff_relation',userID=userID))
    return render_template('write_staff_relation.html',staff=staff)


@app.route('/change_staff_relation/<int:userID>/<int:id>',methods=['GET','POST'])
@login_required
def change_staff_relation(userID,id):
    staff_relation = Staff_relation.query.filter_by(userID=userID,id=id).first()
    staff = Staff.query.filter_by(userID=userID).first()
    if request.method == 'POST':
        company = request.form.get('company')
        position = request.form.get('position')
        phone = request.form.get('phone')
        if phone == '':
            phone = None
        staff_relation.company=company
        staff_relation.position=position
        staff_relation.phone=phone

        db.session.commit()
        flash('更新成功')
        return redirect(url_for('staff_relation',userID=userID))
    return render_template('change_staff_relation.html', staff_relation=staff_relation,staff=staff)


@app.route('/delete_staff_relation/<int:userID>/<int:id>', methods=['POST'])  # 限定只接受POST请求
@login_required  # 登录保护
def delete_staff_relation(userID,id):
    staff_relation = Staff_relation.query.get_or_404(id)
    db.session.delete(staff_relation)
    db.session.commit()
    flash('删除成功')
    return redirect(url_for('staff_relation',userID=userID))


"""
    优化曾代码功能和界面
        部门  -- 添加/department_add （Admin/Root）  
              -- 删除部门/department_delete(Admin/Root)  
              -- 修改/department_alter(Admin/Root)
              -- 查找/info （部门编号/部门名称/电话）
              -- 显示/department（所有人）
        岗位  -- 显示/post(所有人)
              -- 添加/post_add(Admin/Root)
              -- 删除/post_delete(Admin/Root)
              -- 修改/post_alter(Admin/Root)
              -- 查找/info()
"""

@app.route('/department',methods=['GET','POST'])
@login_required  # 登录保护
def department():
    if request.method == 'POST':
        info = request.form.get('info')
        date = request.form.get('date')
        if info == 'departmentID':
            department = Department.query.filter_by(departmentID=date).first()
            if department is None:
                flash('部门编号不存在')
                return redirect(url_for('department'))
            return render_template('department.html', departments=department, info=info)
        if info == 'departmentname':
            department = Department.query.filter_by(departmentname=date).first()
            if department is None:
                flash('部门不存在')
                return redirect(url_for('department'))
            return render_template('department.html', departments=department, info=info)

        if info == 'departmentphone':
            department = Department.query.filter_by(departmentphone=date).first()
            if department is None:
                flash('电话不存在')
                return redirect(url_for('department'))
            return render_template('department.html', departments=department, info=info)
    departments = Department.query.all()

    return render_template('department.html', departments=departments,info = 1)


@app.route('/department_delete/<int:departmentID>',methods=['POST'])
@login_required  # 登录保护
def department_delete(departmentID):
    staff = Staff.query.filter_by(departmentID=departmentID).first()
    if staff is not None:
        flash('该部门内存在员工无法删除')
        return redirect(url_for('department'))
    department = Department.query.get_or_404(departmentID)
    db.session.delete(department)
    db.session.commit()
    flash('删除成功')
    return redirect(url_for('department'))

@app.route('/department_alter/<int:departmentID>',methods=['GET','POST'])
@login_required
def department_alter(departmentID):
    department = Department.query.get_or_404(departmentID)
    departmentnames = Department.query.all()
    if request.method == 'POST':
        departmentname = request.form.get('departmentname')
        departmenttype = request.form.get('departmenttype')
        departmentphone = request.form.get('departmentphone')
        departmentfax = request.form.get('departmentfax')
        if departmentfax == '':
            departmentfax = None
        describe = request.form.get('describe')
        superior = request.form.get('superior')
        department.departmentname = departmentname
        department.departmenttype = departmenttype
        department.departmentphone = departmentphone
        department.departmentfax = departmentfax
        department.describe = describe
        department.superior = superior
        db.session.commit()
        flash('更新成功')
        return redirect(url_for('department'))

    return render_template('department_alter.html', department=department,departmentnames=departmentnames)


@app.route('/department_add', methods=['GET', 'POST'])
@login_required
def department_add():
    if request.method == 'POST':
        departmentname = request.form.get('departmentname')
        departmenttype = request.form.get('departmenttype')
        departmentphone = request.form.get('departmentphone')
        departmentfax = request.form.get('departmentfax')
        if departmentfax == '':
            departmentfax = None
        describe = request.form.get('describe')
        superior = request.form.get('superior')
        establish = request.form.get('establish')
        department = Department(departmentname=departmentname, departmenttype=departmenttype, departmentphone=departmentphone, departmentfax=departmentfax, describe=describe, superior=superior, establish=establish)

        db.session.add(department)
        db.session.commit()
        flash('新建成功')
        return redirect(url_for('department'))
    departmentnames = Department.query.all()
    return render_template('department_add.html',departmentnames=departmentnames)


@app.route('/post',methods=['GET','POST'])
@login_required  # 登录保护
def post():
    if request.method == 'POST':
        info = request.form.get('info')
        date = request.form.get('date')
        if info == 'postID':
            posts = Post.query.filter_by(postID=date).first()
            if department is None:
                flash('岗位编号不存在')
                return redirect(url_for('post'))
            return render_template('post.html', posts=posts, info=info)
        if info == 'postname':
            posts = Post.query.filter_by(postname=date).first()
            if department is None:
                flash('岗位不存在')
                return redirect(url_for('post'))
            return render_template('post.html', posts=posts, info=info)


    posts = Post.query.all()

    return render_template('post.html', posts=posts,info = 1)


@app.route('/post_delete/<int:postID>',methods=['POST'])
@login_required  # 登录保护
def post_delete(postID):
    staff = Staff.query.filter_by(postID=postID).first()
    if staff is not None:
        flash('该岗位内存在员工无法删除')
        return redirect(url_for('post'))
    post = Post.query.get_or_404(postID)
    db.session.delete(post)
    db.session.commit()
    flash('删除成功')
    return redirect(url_for('post'))

@app.route('/post_alter/<int:postID>',methods=['GET','POST'])
@login_required
def post_alter(postID):
    post = Post.query.get_or_404(postID)
    if request.method == 'POST':
        postname = request.form.get('postname')
        posttype = request.form.get('posttype')
        establishment = request.form.get('establishment')
        if establishment == '':
            establishment = None
        post.postname = postname
        post.posttype = posttype
        post.establishment = establishment
        db.session.commit()
        flash('更新成功')
        return redirect(url_for('post'))

    return render_template('post_alter.html', post=post)


@app.route('/post_add', methods=['GET', 'POST'])
@login_required
def post_add():
    if request.method == 'POST':
        postname = request.form.get('postname')
        posttype = request.form.get('posttype')
        establishment = request.form.get('establishment')
        if establishment == '':
            establishment = None
        post = Post(postname=postname, posttype=posttype, establishment=establishment)
        db.session.add(post)
        db.session.commit()
        flash('新建成功')
        return redirect(url_for('post'))
    return render_template('post_add.html')


"""
    试用期管理  
    -- 在试用期员工管理/probation
        -- 未填写过的 填写/write_probation
        -- 修改/change_probation(Admin/Root)
        -- 查询 (userID,username,departmentname,examine_result,startdate,enddate)
    
    -- 正式员工 试用期信息管理/formal 
        -- 查询 (userID,username,departmentname,startdate,enddate)
"""
def notin(staff_probations,probations):
    noin = []

    for staff_probation in staff_probations:
        x = 0
        for probation in probations:
            if staff_probation.userID == probation.userID:
                x = 1
        if x == 0:
            nowstaff = {}
            nowstaff = staff_probation
            noin.append(nowstaff)
    return noin

@app.route('/probation',methods=['GET','POST'])
@login_required
def probation():
    staff_probations = Staff_probation.query.all()
    probations = Probation.query.all()
    noins = notin(staff_probations, probations)
    if request.method == 'POST':
        info = request.form.get('info')
        date = request.form.get('date')
        if info == 'userID':
            staffs = Staff.query.filter_by(userID=date,now=True).first()
            if staffs is None:
                flash('员工号不存在')
                return redirect(url_for('probation'))
            departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
            staff_probations = Staff_probation.query.filter_by(userID=date).first()
            probations = Probation.query.filter(Probation.userID == date and Probation.examine_result != '转正').first()
            return render_template('probation.html', staffs=staffs, departments=departments,probations=probations ,staff_probations=staff_probations, info=info)

        if info == 'username':
            staffs = Staff.query.filter_by(username=date,now=True).first()
            if staffs is None:
                flash('员工不存在')
                return redirect(url_for('probation'))
            departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
            staff_probations = Staff_probation.query.filter_by(userID=staffs.userID).first()
            probations = Probation.query.filter(Probation.userID == staffs.userID and Probation.examine_result != '转正').first()
            return render_template('probation.html', staffs=staffs, departments=departments,probations=probations ,staff_probations=staff_probations, info=info)

        if info == 'departmentname':
            departments = Department.query.filter_by(departmentname=date).first()
            if departments is None:
                flash('部门不存在')
                return redirect(url_for('probation'))
            staffs = Staff.query.filter_by(departmentID=departments.departmentID,now=True).all()
            staff_probations = Staff_probation.query.all()
            probations = Probation.query.filter(Probation.examine_result != '转正').all()
            return render_template('probation.html', staffs=staffs, departments=departments,probations=probations ,staff_probations=staff_probations,noins=noins, info=info)

        if info == 'examine_result':
            probations = Probation.query.filter(Probation.examine_result==date and Probation.examine_result != '转正').all()
            if len(probations) == 0:
                flash('状态不存在')
                return redirect(url_for('probation'))
            departments = Department.query.all()
            staff_probations = Staff_probation.query.all()
            staffs = Staff.query.filter_by(now=True).all()
            return render_template('probation.html', staffs=staffs, departments=departments,probations=probations ,staff_probations=staff_probations,noins=noins, info=info)

        if info == 'startdate':
            staff_probations = Staff_probation.query.filter(Staff_probation.startdate >= date).all()
            if len(staff_probations)==0 :
                flash('此日期之后没有员工')
                return redirect(url_for('probation'))
            departments = Department.query.all()
            probations = Probation.query.filter(Probation.examine_result != '转正').all()
            staffs = Staff.query.filter_by(now=True).all()
            return render_template('probation.html', staffs=staffs, departments=departments,probations=probations ,staff_probations=staff_probations,noins=noins, info=info)

        if info == 'enddate':
            staff_probations = Staff_probation.query.filter(Staff_probation.enddate <= date).all()
            if len(staff_probations) == 0:
                flash('此日期之前没有员工')
                return redirect(url_for('probation'))
            departments = Department.query.all()
            probations = Probation.query.filter(Probation.examine_result != '转正').all()
            staffs = Staff.query.filter_by(now=True).all()
            noins = notin(staff_probations, probations)
            return render_template('probation.html', staffs=staffs, departments=departments,probations=probations ,staff_probations=staff_probations,noins=noins, info=info)

    staffs = Staff.query.filter_by(now=True).all()
    probations = Probation.query.filter(Probation.examine_result != '转正').all()
    departments = Department.query.all()

    return render_template('probation.html', staffs=staffs, departments=departments,staff_probations=staff_probations, probations=probations,noins=noins, info=1)



@app.route('/write_probation/<int:userID>',methods=['GET','POST'])
@login_required
def write_probation(userID):
    if request.method=='POST':
        userID = userID
        examine_remark = request.form.get('examine_remark')
        examine_result = request.form.get('examine_result')
        disposedate = request.form.get('disposedate')
        remark = request.form.get('remark')

        probation = Probation(userID=userID,examine_remark=examine_remark,examine_result=examine_result,
                              disposedate=disposedate,remark=remark)

        db.session.add(probation)
        db.session.commit()

        flash('填写成功')
        if examine_result == '不予录用':
            return redirect(url_for('write_staff_dimission',userID=userID))
        return redirect(url_for('probation'))
    staff = Staff.query.filter_by(userID=userID).first()
    return render_template('write_probation.html',staff=staff)

@app.route('/change_probation/<int:userID>',methods=['GET','POST'])
@login_required
def change_probation(userID):
    probation = Probation.query.filter_by(userID=userID).first()
    if request.method=='POST':
        examine_remark = request.form.get('examine_remark')
        examine_result = request.form.get('examine_result')
        disposedate = request.form.get('disposedate')
        remark = request.form.get('remark')
        probation.examine_remark=examine_remark
        probation.examine_result=examine_result
        probation.disposedate=disposedate
        probation.remark=remark
        db.session.commit()

        flash('修改成功')
        if examine_result == '不予录用':
            return redirect(url_for('write_staff_dimission',userID=userID))
        return redirect(url_for('probation'))
    staff = Staff.query.filter_by(userID=userID).first()
    return render_template('change_probation.html',staff=staff,probation=probation,userID=userID)

@app.route('/formal',methods=['GET','POST'])
@login_required
def formal():
    staff_probations = Staff_probation.query.all()
    if request.method == 'POST':
        info = request.form.get('info')
        date = request.form.get('date')
        if info == 'userID':
            staffs = Staff.query.filter_by(userID=date,now=True).first()
            if staffs is None:
                flash('员工号不存在')
                return redirect(url_for('formal'))
            departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
            staff_probations = Staff_probation.query.filter_by(userID=date).first()
            probations = Probation.query.filter(Probation.userID == date and Probation.examine_result == '转正').first()
            return render_template('formal.html', staffs=staffs, departments=departments,probations=probations ,staff_probations=staff_probations, info=info)

        if info == 'username':
            staffs = Staff.query.filter_by(username=date,now=True).first()
            if staffs is None:
                flash('员工不存在')
                return redirect(url_for('formal'))
            departments = Department.query.filter_by(departmentID=staffs.departmentID).first()
            staff_probations = Staff_probation.query.filter_by(userID=staffs.userID).first()
            probations = Probation.query.filter(Probation.userID == staffs.userID and Probation.examine_result == '转正').first()
            return render_template('formal.html', staffs=staffs, departments=departments,probations=probations ,staff_probations=staff_probations, info=info)

        if info == 'departmentname':
            departments = Department.query.filter_by(departmentname=date).first()
            if departments is None:
                flash('部门不存在')
                return redirect(url_for('formal'))
            staffs = Staff.query.filter_by(departmentID=departments.departmentID,now=True).all()
            staff_probations = Staff_probation.query.all()
            probations = Probation.query.filter(Probation.examine_result == '转正').all()
            return render_template('formal.html', staffs=staffs, departments=departments,probations=probations ,staff_probations=staff_probations, info=info)


        if info == 'startdate':
            staff_probations = Staff_probation.query.filter(Staff_probation.startdate >= date).all()
            if len(staff_probations)==0 :
                flash('此日期之后没有员工')
                return redirect(url_for('probation'))
            departments = Department.query.all()
            probations = Probation.query.filter(Probation.examine_result == '转正').all()
            staffs = Staff.query.filter_by(now=True).all()
            return render_template('formal.html', staffs=staffs, departments=departments,probations=probations ,staff_probations=staff_probations, info=info)

        if info == 'enddate':
            staff_probations = Staff_probation.query.filter(Staff_probation.enddate <= date).all()
            if len(staff_probations) == 0:
                flash('此日期之前没有员工')
                return redirect(url_for('formal'))
            departments = Department.query.all()
            probations = Probation.query.filter(Probation.examine_result == '转正').all()
            staffs = Staff.query.filter_by(now=True).all()
            noins = notin(staff_probations, probations)
            return render_template('formal.html', staffs=staffs, departments=departments,probations=probations ,staff_probations=staff_probations, info=info)

    staffs = Staff.query.filter_by(now=True).all()
    probations = Probation.query.filter(Probation.examine_result == '转正').all()
    departments = Department.query.all()

    return render_template('formal.html', staffs=staffs, departments=departments,staff_probations=staff_probations, probations=probations, info=1)


"""
报表管理    -- 员工报表/report_form(Admin/Root)
            -- 新员工/report_form_newstaff(Admin/Root)
            -- 离职员工/report_form_dimission(Admin/Root)
            -- 月报/report_form_personnnel_monthly/(Admin/Root)
            
            -- 查询/begindate,enddate,departmentname
"""

@app.route('/report_form')
@login_required
def report_form():
    departments = Department.query.all()
    return render_template('report_form.html',departments=departments)

#新聘员工报表
@app.route('/report_form_newstaff/<int:departmentID>', methods=['GET','POST'])
@login_required
def report_form_newstaff(departmentID):

    # 获取当前时间
    now_time = datetime.datetime.now()
    # 格式化时间字符串
    begin_date = now_time.strftime("%Y-%m-1")
    end_date = now_time.strftime("%Y-%m-%d")
    if departmentID == 0 :
        department = Department.query.all()
        posts = Post.query.all()
        staffs = Staff.query.filter(Staff.hiredate >= begin_date).filter(Staff.hiredate <= end_date).filter_by(now=True).all()

        if request.method == 'POST':
            begin_date = request.form.get('begin_date')
            end_date = request.form.get('end_date')
            staffs = Staff.query.filter(Staff.hiredate >= begin_date).filter(Staff.hiredate <= end_date).filter_by(
                now=True).all()
            return render_template('report_form_newstaff.html',posts=posts,departmentID=departmentID, departments=department, staffs=staffs)
        return render_template('report_form_newstaff.html',posts=posts,departmentID=departmentID, departments=department, staffs=staffs)
    else:
        department = Department.query.filter_by(departmentID=departmentID).all()
        staffs = Staff.query.filter(Staff.hiredate >= begin_date).filter(Staff.hiredate <= end_date).filter_by(departmentID=departmentID,now=True).all()
        posts = Post.query.all()
        begin_date = 0
        end_date = 0
        if request.method == 'POST':
            begin_date = request.form.get('begin_date')
            end_date = request.form.get('end_date')
            staffs = Staff.query.filter(Staff.hiredate >= begin_date).filter(Staff.hiredate <= end_date).filter_by(now=True,departmentID=departmentID).all()
            return render_template('report_form_newstaff.html',posts=posts,departmentID=departmentID, departments=department, staffs=staffs)
        return render_template('report_form_newstaff.html',posts=posts,departmentID=departmentID, departments=department, staffs=staffs)


#离职员工报表
@app.route('/report_form_dimission/<int:departmentID>', methods=['GET','POST'])
@login_required
def report_form_dimission(departmentID):
    # 获取当前时间
    now_time = datetime.datetime.now()
    # 格式化时间字符串
    begin_date = now_time.strftime("%Y-%m-1")
    end_date = now_time.strftime("%Y-%m-%d")
    if departmentID == 0 :
        staff_dimissions = Staff_dimission.query.filter(Staff_dimission.termdate >= begin_date).filter(Staff_dimission.termdate <= end_date).all()
        department = Department.query.all()
        posts = Post.query.all()
        staffs = Staff.query.filter_by(now=False).all()
        if request.method == 'POST':
            begin_date = request.form.get('begin_date')
            end_date = request.form.get('end_date')
            staff_dimissions = Staff_dimission.query.filter(Staff_dimission.termdate >= begin_date).filter(Staff_dimission.termdate <= end_date).all()
            return render_template('report_form_dimission.html',staff_dimissions=staff_dimissions,posts=posts,departmentID=departmentID, departments=department, staffs=staffs)
        return render_template('report_form_dimission.html',staff_dimissions=staff_dimissions,posts=posts,departmentID=departmentID, departments=department, staffs=staffs)
    else:
        staff_dimissions = Staff_dimission.query.filter(Staff_dimission.termdate >= begin_date).filter(Staff_dimission.termdate <= end_date).all()
        department = Department.query.filter_by(departmentID=departmentID).all()
        staffs = Staff.query.filter_by(departmentID=departmentID,now=False).all()
        posts = Post.query.all()
        if request.method == 'POST':
            begin_date = request.form.get('begin_date')
            end_date = request.form.get('end_date')
            staff_dimissions = Staff_dimission.query.filter(Staff_dimission.termdate >= begin_date).filter(Staff_dimission.termdate <= end_date).all()
            return render_template('report_form_dimission.html',staff_dimissions=staff_dimissions,posts=posts,departmentID=departmentID, departments=department, staffs=staffs)
        return render_template('report_form_dimission.html',staff_dimissions=staff_dimissions,posts=posts,departmentID=departmentID, departments=department, staffs=staffs)

#人月报表
@app.route('/report_form_personnnel_monthly', methods=['GET','POST'])
@login_required
def report_form_personnnel_monthly():

    # 获取当前时间
    now_time = datetime.datetime.now()
    # 格式化时间字符串
    begin_date = now_time.strftime("%Y-%m-1")
    end_date = now_time.strftime("%Y-%m-%d")
    report_form_monthly=[]


    departments = Department.query.all()
    for department in departments:
        end_person = Staff.query.filter_by(departmentID=department.departmentID,now=True).all()
        leave_persons = Staff.query.filter_by(departmentID=department.departmentID,now=False).all()
        dimission_persons = Staff_dimission.query.filter(Staff_dimission.termdate >= begin_date).filter(Staff_dimission.termdate <= end_date).all()
        new_person = Staff.query.filter(Staff.hiredate >= begin_date).filter(Staff.hiredate <= end_date).filter_by(
            now=True,departmentID=department.departmentID).all()
        postgraduate = Staff.query.filter_by(departmentID=department.departmentID,highest_degree='研究生',now=True).all()
        undergraduate = Staff.query.filter_by(departmentID=department.departmentID,highest_degree='本科', now=True).all()
        junior_college = Staff.query.filter_by(departmentID=department.departmentID,highest_degree='大专', now=True).all()
        high_school = Staff.query.filter_by(departmentID=department.departmentID,highest_degree='高中及以下', now=True).all()
        dimission_person_number = 0
        for dimission_person in dimission_persons:
            for leave_person in leave_persons:
                if leave_person.userID == dimission_person.userID:
                    dimission_person_number +=1
        begin_person = len(end_person)+dimission_person_number
        end_person = len(end_person)
        new_person = len(new_person)
        postgraduate = len(postgraduate)
        undergraduate = len(undergraduate)
        junior_college = len(junior_college)
        high_school = len(high_school)
        personnnel_monthly = {
            'department':department.departmentname,
            'begin_persons':begin_person,
            'end_persons':end_person,
            'new_persons':new_person,
            'dimission_persons':dimission_person_number,
            'postgraduates':postgraduate,
            'undergraduates':undergraduate,
            'junior_colleges':junior_college,
            'high_schools':high_school
        }
        report_form_personnnel={}
        report_form_personnnel=personnnel_monthly
        report_form_monthly.append(report_form_personnnel)
    print(report_form_monthly)
    if request.method == 'POST':
        begin_date = request.form.get('begin_date')
        end_date = request.form.get('end_date')
        report_form_monthly = []

        departments = Department.query.all()
        for department in departments:
            end_person = Staff.query.filter_by(departmentID=department.departmentID, now=True).all()
            leave_persons = Staff.query.filter_by(departmentID=department.departmentID, now=False).all()
            dimission_persons = Staff_dimission.query.filter(Staff_dimission.termdate >= begin_date).filter(
                Staff_dimission.termdate <= end_date).all()
            new_person = Staff.query.filter(Staff.hiredate >= begin_date).filter(Staff.hiredate <= end_date).filter_by(
                now=True,departmentID=department.departmentID).all()
            postgraduate = Staff.query.filter_by(departmentID=department.departmentID,highest_degree='研究生', now=True).all()
            undergraduate = Staff.query.filter_by(departmentID=department.departmentID,highest_degree='本科', now=True).all()
            junior_college = Staff.query.filter_by(departmentID=department.departmentID,highest_degree='大专', now=True).all()
            high_school = Staff.query.filter_by(departmentID=department.departmentID,highest_degree='高中及以下', now=True).all()
            dimission_person_number = 0
            for dimission_person in dimission_persons:
                for leave_person in leave_persons:
                    if leave_person.userID == dimission_person.userID:
                        dimission_person_number += 1
            begin_person = len(end_person) + dimission_person_number
            end_person = len(end_person)
            new_person = len(new_person)
            postgraduate = len(postgraduate)
            undergraduate = len(undergraduate)
            junior_college = len(junior_college)
            high_school = len(high_school)
            personnnel_monthly = {
                'department': department.departmentname,
                'begin_persons': begin_person,
                'end_persons': end_person,
                'new_persons': new_person,
                'dimission_persons': dimission_person_number,
                'postgraduates': postgraduate,
                'undergraduates': undergraduate,
                'junior_colleges': junior_college,
                'high_schools': high_school
            }
            report_form_personnnel = {}
            report_form_personnnel = personnnel_monthly
            report_form_monthly.append(report_form_personnnel)
        return render_template('report_form_personnnel_monthly.html',report_form_monthlys=report_form_monthly,begin_date=begin_date,end_date=end_date)
    return render_template('report_form_personnnel_monthly.html',report_form_monthlys=report_form_monthly,begin_date=begin_date,end_date=end_date)

